import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'

const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView,
    redirect: 'home',
    /* 子路由 */
    children:[
      {path: 'home',name: 'Home',meta:{name: '主页'},component:() => import('../views/Home.vue')},
    ]
  },
  {
    path: '/login',
    name: 'Login',
    meta: {name: '登录'},
    component: () => import('../views/Login.vue')
  },
  {
    path: '/:catchAll(.*)',
    name: '404',
    component: () => import('../views/404.vue'),
    meta: {name: '无法访问'},
  },
];

const router = createRouter({
  mode: 'history',
  history: createWebHistory(process.env.BASE_URL),
  routes
})

function activeRouter(){
  let userStr = sessionStorage.getItem('user-data');
  let user = JSON.parse(userStr);
  if (user) {
    let root = {
      path: '/',
      name: '首页',
      component: HomeView,
      redirect: '/home',
      children: [],
    }
    // 一级
    user.permList.forEach(p1 => {
      if (p1.perms == null) {
        let obj = {
          path: p1.visitPath,
          name: p1.path,
          meta: {name: p1.name},
          component: () => import("@/views/" + p1.path),
        };
        root.children.push(obj);
      } else {
        // 二级
        p1.perms.forEach(p2 => {
          let obj = {
            path: p2.visitPath,
            name: p2.path,
            meta:{name: p2.name},
            component: ()=> import("@/views/"+ p2.path),
          }
          root.children.push(obj);
        });
      }
    });
    if (router) {
      router.addRoute(root);
    }
  }
}
activeRouter();

// 路由守卫
router.beforeEach((to, from, next) => {
  /*
       to: 到达的路由信息
       from: 来源的路由信息
       next: 跳转路由的函数
   */
  let user = JSON.parse(sessionStorage.getItem('user-data'));
  if (user == null) {
    if (to.path === '/login') {
      next()
    } else {
      next('/login')
    }
  } else {
    if (routes.indexOf(to.path) > -1) {
      next('/login')
    } else {
      next()
    }
  }
});
export default router
